//获取系统信息
function getSystemInfo(callBack) {
    wx.getSystemInfo({
        success: function (res) {
            callBack(res);
        }
    });
}
//设置本地缓存
function setStorage(key, data) {
    wx.setStorageSync(key, data)
}
//获取本地缓存
function getStorage(key) {
    return wx.getStorageSync(key)
}

function formatAllTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
   
}

function formatTime(date) {
    var hour = date.getHours()
    var minute = date.getMinutes()
    return [hour, minute].map(formatNumber).join(':')
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
// ajax
const http = (loading, method, url, data, callBack)=>{
    var token = getStorage("token");  
    if (loading) {showLoading("加载中")};
    wx.request({
        method: method,
        url: url,
        data: data,
        header:{
            'app_id': "wx8c982a33de8acb8c",
            'token': token,
            'Content-type': 'application/json' // 默认值
        },
        success:function(res){
            hideToast();
            if (res.statusCode == 200) {
                if (res.data.code == 0) {
                    callBack(res.data.data)
                }
                if (res.data.code == 1) {
                    failToast(res.data.message);
                }
                if (res.data.code == 2) {
                    wx.navigateTo({
                        url: '../login/login',
                    })
                }
            }
            if (res.statusCode == 404){
                failToast(res.data.message);
            }
        },
        fail:function(err){
            hideToast();
            failToast("服务器异常！");
        }
    })
}


/**
 * 微信登录获取openID
 */
function getOpenID(appid, secret,callBack){
    wx.login({
        success: function (loginCode) {
            console.log("loginCode.code==" + loginCode.code)
            //调用request请求api转换登录凭证  
            var url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+ secret+"&js_code="+loginCode.code+"&grant_type=authorization_code"
            console.log("url========"+url)
            wx.request({
                url: url,
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    console.log("getOpenID==========" + res.data.openid)
                    callBack(res.data.openid) //获取openid  
                }
            })
        }
    })
} 
/**
 * 发起微信支付
 */
function pay(info,callBack){
    wx.requestPayment({
        'timeStamp': info.timeStamp,
        'nonceStr': info.nonceStr,
        'package': info.package,
        'signType': 'MD5',
        'paySign': info.paySign,
        'success': function (res) {
            callBack(res);
        },
        'fail': function (res) {
            
        }

    })
} 
// scope.userInfo	wx.getUserInfo	用户信息
// scope.userLocation	wx.getLocation, wx.chooseLocation	地理位置
// scope.address	wx.chooseAddress	通讯地址
// scope.invoiceTitle	wx.chooseInvoiceTitle	发票抬头
// scope.werun	wx.getWeRunData	微信运动步数
// scope.record	wx.startRecord	录音功能
// scope.writePhotosAlbum	wx.saveImageToPhotosAlbum, wx.saveVideoToPhotosAlbum	保存到相册
//用户拒绝授权，获取用户当前设置，重新授权
function getPermission(typeName, callBack) {
    var that = this;
    wx.getSetting({
        success(res) {
            if (res.authSetting[typeName] == undefined) {
                console.log("----->"
                    + "res.authSetting[" + typeName + "]===" + res.authSetting[typeName]);
                return;
            }
            //用户同意授权
            else if (res.authSetting[typeName]) {
                callBack();
            }
            //用户拒绝授权
            else {
                wx.openSetting({
                    //用户设置完成之后，需要再次判断用户是否授权
                    success: (res) => {
                        getPermission(typeName, callBack);
                    },
                })
            }

        }
    })
}



//图库选择图片或者拍照
// count:1-9
function chooseImage(callBack, count) {
    wx.chooseImage({
        count: count, // 最多可以选择的图片张数
        success: function (res) {
            callBack(res);
        }
    })
}
//图片上传
function uploadFile( filePath, callBack, fromData) {
    var uploadTask = wx.uploadFile({
        url: "https://shop.hx2lm.com/api/user/upload",
        filePath: filePath,
        name: 'file',
        formData: fromData,
        success: function (res) {
            callBack(res);
        },
        fail: function (res) {
        }
    })
    uploadTask.onProgressUpdate((res) => {
        var progress = res.progress;
        console.log(progress);
        wx.showLoading({
            title: "上传中" + res.progress + '%',
            mask: true,
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
        })

    })
}
// 手机号验证
function IsMobile(phone) {
    var rules = /^((\+?86)|(\(\+86\)))?(13[0123456789][0-9]{8}|14[0123456789][0-9]{8}|15[0123456789][0-9]{8}|17[0123456789][0-9]{8}|18[0123456789][0-9]{8}|147[0-9]{8}|1349[0-9]{7})$/;
    return rules.test(phone);
}

//确认？取消 弹框
function showModal(title, content, confirmCallBack) {
    wx.showModal({
        title: title,
        content: content,
        success: function (res) {
            if (res.confirm) {
                confirmCallBack()
            } else if (res.cancel) {
               
            }
        }
    })
}

//操作成功的提示 
function successToast(title) {
    wx.showLoading({
        title: title,
        icon: 'success',
        duration: 1000
    })
}

//操作失败的提示
function failToast(title) {
    wx.showLoading({
        title: title,
        image: "/icons/error.png",
        duration: 1000
    })
}


//加载框---一般用于网络请求，请求成功之后需要调用hideToast
function showLoading(title) {
    wx.showLoading({
        title: title,
        mask: true
    })
}


//隐藏加载框
function hideToast() {
    wx.hideLoading();
}

// 设置页面标题
function setNavigationBarTitle(setTitle) {
    wx.setNavigationBarTitle({
        title: setTitle,
    });
}
// 返回顶部按钮显示隐藏
function scrollTopFun(e, callback1, callback2) {
    if (e.detail.scrollTop > 500) {
        callback1();
    } else {
        callback2();
    }
}
// 点击按钮返回顶部
function goTopFun(_top, callback) {
    if (_top == 1) {
        _top = 0;
    } else {
        _top = 1;
    }
    callback();
}
// 拨打电话
function makePhone(phonenum) {
    wx.makePhoneCall({
        phoneNumber: phonenum
    })
}
//地址管理
function addMsg() {
    wx.chooseAddress({
        success: function (e) {
            console.log(e.detailInfo);
        },
        fail: function () {
            getPermission("scope.address", function () {
                addMsg();
            })
        },

    })
}
//选择地址
function chooseAddress(callBack){
    wx.chooseAddress({
        success: function (e) {
            callBack(e);
        },
        fail: function () {
            getPermission("scope.address", function () {
                chooseAddress(callBack);
            })
        },

    })
}
module.exports = {
    http,
    formatTime,
    getSystemInfo,
    getPermission,
    chooseImage,
    uploadFile,
    IsMobile,
    successToast,
    failToast,
    showLoading,
    hideToast,
    setNavigationBarTitle,
    scrollTopFun ,
    goTopFun,
    makePhone,
    addMsg,
    getStorage,
    setStorage,
    showModal,
    chooseAddress,
    getOpenID,
    pay,
    formatAllTime,
}
